package www.bwsensing.com.common.netty;

import com.alibaba.cola.exception.Assert;
import lombok.Data;
import www.bwsensing.com.common.mqtt.MqttPushClient;
import www.bwsensing.com.common.netty.handler.NettyTcpServerHandler;
import www.bwsensing.com.common.netty.initializer.NettyTcpInitializer;
import www.bwsensing.com.service.collection.database.dataobject.ServiceData;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务初始化工厂
 * @author macos-zyj
 */
@Data
public class NettyTcpServerFactory {
    private static final Map<Integer, NettyTcpServerImpl> NETTY_TCP_SERVICE = new ConcurrentHashMap<>();

    public static NettyTcpServerImpl getNettyServer(ServiceData serviceData, MqttPushClient mqttPushClient){
        Assert.notNull(serviceData, "配置信息不能为空!");
        int listenPort = Integer.parseInt(serviceData.getServiceValue());
        if (null != NETTY_TCP_SERVICE.get(listenPort)) {
            return NETTY_TCP_SERVICE.get(listenPort);
        }  else {
            NettyTcpServerHandler serverHandler = new NettyTcpServerHandler(serviceData, mqttPushClient);
            NettyTcpInitializer tcpInitializer = new NettyTcpInitializer(serverHandler);
            NettyTcpServerImpl runServer = new NettyTcpServerImpl(listenPort,tcpInitializer);
            NETTY_TCP_SERVICE.put(listenPort,runServer);
            return runServer;
        }
    }
}
